<?php
/**
 * Created by PhpStorm.
 * User: idcu
 * Date: 2016/3/2
 * Time: 12:38
 */
namespace Admin\Model;
use IDCU\Model\RelationModel;

class RegionModel extends RelationModel
{
    protected $tableName='prov_city_area';

    public function cascade(){
        if(!S('region_cascade')){
            $data = $this->select();
            foreach($data as $v) {
                if ($v['area_level'] == 3) {
                    $d['id'] = $v['area_no'];
                    $d['name'] = $v['area_name'];
                    $d['code'] = $v['area_code'];
                    $d['type'] = $v['type_name'];
                    $city_area[$v['parent_no']]['data'][$v['area_no']] = $d;
                    //城市ID级联下属区县资料
                }
            }
            foreach($data as $v) {
                if ($v['area_level'] == 2) {
                    $d['id'] = $v['area_no'];
                    $d['name'] = $v['area_name'];
                    $d['code'] = $v['area_code'];
                    $d['type'] = $v['type_name'];
                    $prov_city_area[$v['parent_no']]['data'][$v['area_no']] = $d;
                    $prov_city_area[$v['parent_no']]['data'][$v['area_no']]['data'] = $city_area[$v['area_no']]['data'];
                    //省市ID级联下属城市资料，进一步级联区县资料
                }
            }
            foreach($data as $v){
                if($v['area_level'] == 1){
                    $d['id'] = $v['area_no'];
                    $d['name'] = $v['area_name'];
                    $d['code'] = $v['area_code'];
                    $d['type'] = $v['type_name'];
                    $result[$v['area_no']] = $d;
                    $result[$v['area_no']]['data'] = $prov_city_area[$v['area_no']]['data'];
                    //省市资料级联下属城市资料，进一步级联区县资料
                }
            }
            foreach($result as $k=>$v){
                if($v['type'] == '市'){
                    $d = $result[$k]['data'];
                    unset($result[$k]['data']);
                    $result[$k]['data'][$k] = $result[$k];
                    $result[$k]['data'][$k]['data'] = $d;
                    //将只有两级的省市，复制省市到第二级，统一成为省市区三级级联格式
                }
            }
            S('region_cascade',$result);
            //缓存
        }
        return S('region_cascade');
    }

    public function regoup(){
        $data = $this->select();
        foreach($data as $k=>$v){
            $result[$v['area_no']] = $v;
        }
        S('region',$result);
        return S('region');
    }

    public function getRegion($regionNo){
        if(!S('region')){
            $this->regoup();
        }
        return S('region')[$regionNo];
    }
}